package com.shijiezhijia.sjzjapp.demo;

import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.content.res.loader.ResourcesLoader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

public class ResourceHelper {

    private AssetManager mAssetManager;
    private Resources mResources;
    private LayoutInflater mInflate;
    private ClassLoader mClassLoader;

    public void initAssetManager(Context context,String apkPath) {
        try {
            Log.e("ResourceHelper",apkPath);
            // 主resources
            Resources appRes = context.getResources();
            // 反射创建AssetManager
            AssetManager manager = AssetManager.class.newInstance();
            // 通过反射调用addAssetPath方法设置 资源apk的路径
            ReflectionUtil.invokeMethod(manager, "android.content.res.AssetManager", "addAssetPath", new Class[]{String.class}, apkPath);
            mAssetManager = manager;
            // 资源apk的resources 根据当前设备的显示器信息与配置创建Resources,
            mResources = new Resources(manager,appRes.getDisplayMetrics(),appRes.getConfiguration());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    private String getPackageName() {
        return "com.shijiezhijia.sjzjapp.resapp";
    }

    public View getResApkLayout(Context context,String layoutName) {
        if(mResources != null) {
            int layoutId = mResources.getIdentifier(layoutName,"layout",getPackageName());
            View view = LayoutInflater.from(context).inflate(mResources.getLayout(layoutId),null,false);
            return view;
        }
        return null;
    }

}
